package com.gmrz.uaf.server;

import com.gmrz.service.challengestore.ChallengeStoreException;
import com.gmrz.service.challengestore.ChallengeStoreService;
import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.util.Convert;
import com.gmrz.util.Strings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
 * Created by gmrz-ops on 2018/9/13.
 */
public class MonitorFilter implements Filter {
    private static final Logger LOG = LogManager.getLogger(MonitorFilter.class);
    private static final String REQUEST_COUNT = "uaf.request.count";
    private static String hostName;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ChallengeStoreService challengeStoreService = GuiceUtil.getProcessorInjector().getInstance(ChallengeStoreService.class);
        try {
            hostName = InetAddress.getLocalHost().getHostName().toString();
            challengeStoreService.deleteRedisValue(Constants.CONCURRENT_REQUEST_COUNT+"."+hostName);
            challengeStoreService.deleteAll(REQUEST_COUNT+"."+hostName+".*");
        } catch (Exception e) {
            MonitorFilter.LOG.error("init error",e);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ChallengeStoreService challengeStoreService = GuiceUtil.getProcessorInjector().getInstance(ChallengeStoreService.class);
        try {
            if (!Strings.isNotBlank(hostName)){
                hostName = InetAddress.getLocalHost().getHostName().toString();
            }
            challengeStoreService.incr(Constants.CONCURRENT_REQUEST_COUNT+"."+hostName);
            challengeStoreService.incr(REQUEST_COUNT+"."+hostName+"."+ Convert.getCurrentDate());
        } catch (ChallengeStoreException e) {
            MonitorFilter.LOG.error("concurrent request_count incr error",e);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            try {
                challengeStoreService.decr(Constants.CONCURRENT_REQUEST_COUNT+"."+hostName);
            } catch (ChallengeStoreException e) {
                MonitorFilter.LOG.error("concurrent request_count decr error",e);
            }
        }

    }

    @Override
    public void destroy() {

    }


}
